/**
 * 
 */
package t4j.concurrency.deadlock;

import java.util.Random;
import java.util.concurrent.TimeUnit;

//哲学家
public class Philosopher implements Runnable {

	private Chopstick left;
	private Chopstick right;
	private final int id;
	private final int ponderFactor;//思考的时间
	private Random rand = new Random(47);

	private void pause() throws InterruptedException {
		if (ponderFactor == 0)
			return;

		TimeUnit.MILLISECONDS.sleep(rand.nextInt(ponderFactor * 250));
	}

	public Philosopher(Chopstick left, Chopstick right, int ident, int ponder) {
		this.left = left;
		this.right = right;
		id = ident;
		ponderFactor = ponder;
	}

	@Override
	public void run() {

		try {
			while (!Thread.interrupted()) {
				System.out.println(this + " " + "thinking");

				pause();//停下来，思考

				right.take();
				
				System.out.println(this + " " + "grabbing right");

				left.take();

				System.out.println(this + " " + "grabbing left");			

				pause();
				
				System.out.println(this + " " + "eating");
				right.drop();
				left.drop();
			}
		} catch (InterruptedException e) {
			System.out.println(this + " " + "exiting via interrupt");
		}
	}

	@Override
	public String toString() {
		return "Philosopher " + id;
	}
}


